<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Babylon.js AssetContainer 完整示例</title>
    <script src="https://cdn.babylonjs.com/babylon.js"></script>
    <script src="https://cdn.babylonjs.com/gui/babylon.gui.min.js"></script>
    <style>
        body { margin: 0; overflow: hidden; }
        canvas { width: 100%; height: 100%; }
        .controls {
            position: absolute;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
            display: flex;
            gap: 10px;
            z-index: 10;
        }
        button {
            padding: 10px 15px;
            font-size: 16px;
            cursor: pointer;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
        }
        button:hover {
            background-color: #45a049;
        }
        .scene-selector {
            position: absolute;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            z-index: 10;
        }
    </style>
</head>
<body>
    <canvas id="renderCanvas"></canvas>
    <div class="scene-selector">
        <select id="sceneSelector">
            <option value="mainMenu">主菜单</option>
            <option value="scene1">场景 1 (骷髅)</option>
            <option value="scene2">场景 2 (机器人)</option>
        </select>
    </div>
    <div class="controls">
        <button id="loadBtn">加载场景</button>
        <button id="unloadBtn">卸载场景</button>
        <button id="cloneBtn">克隆模型</button>
    </div>

    <script>
        // 初始化引擎和画布
        const canvas = document.getElementById('renderCanvas');
        const engine = new BABYLON.Engine(canvas, true);
        
        // 场景管理器类
        class SceneManager {
            constructor(engine) {
                this.engine = engine;
                this.currentScene = null;
                this.currentSceneName = null;
                this.scenes = {};
                this.assetContainers = {};
                this.currentInstances = [];
                
                // 创建主场景
                this.mainScene = new BABYLON.Scene(engine);
                this.mainScene.clearColor = new BABYLON.Color3(0.2, 0.3, 0.4);
                
                // 设置主场景相机
                this.mainCamera = new BABYLON.ArcRotateCamera(
                    "mainCamera", 
                    -Math.PI / 2, 
                    Math.PI / 2.5, 
                    10, 
                    BABYLON.Vector3.Zero(), 
                    this.mainScene
                );
                this.mainCamera.attachControl(canvas, true);
                
                // 设置主场景光源
                this.mainLight = new BABYLON.HemisphericLight(
                    "mainLight", 
                    new BABYLON.Vector3(0, 1, 0), 
                    this.mainScene
                );
                this.mainLight.intensity = 0.7;
                
                // 注册场景
                this.registerScene("mainMenu", {
                    assetUrl: "https://playground.babylonjs.com/scenes/Dude/",
                    assetFilename: "dude.babylon",
                    setupCamera: (scene) => {
                        const camera = new BABYLON.ArcRotateCamera(
                            "menuCamera", 
                            -Math.PI / 2, 
                            Math.PI / 2.5, 
                            15, 
                            BABYLON.Vector3.Zero(), 
                            scene
                        );
                        camera.attachControl(canvas, true);
                        return camera;
                    }
                });
                
                this.registerScene("scene1", {
                    assetUrl: "https://playground.babylonjs.com/scenes/",
                    assetFilename: "skull.babylon",
                    setupCamera: (scene) => {
                        const camera = new BABYLON.ArcRotateCamera(
                            "scene1Camera", 
                            -Math.PI / 2, 
                            Math.PI / 2.5, 
                            10, 
                            BABYLON.Vector3.Zero(), 
                            scene
                        );
                        camera.attachControl(canvas, true);
                        return camera;
                    }
                });
                
                this.registerScene("scene2", {
                    assetUrl: "https://playground.babylonjs.com/scenes/Dude/",
                    assetFilename: "dude.babylon",
                    setupCamera: (scene) => {
                        const camera = new BABYLON.ArcRotateCamera(
                            "scene2Camera", 
                            -Math.PI / 2, 
                            Math.PI / 2.5, 
                            8, 
                            new BABYLON.Vector3(0, 1, 0), 
                            scene
                        );
                        camera.attachControl(canvas, true);
                        return camera;
                    }
                });
                
                // 创建GUI系统
                this.createGUI();
            }
            
            // 创建GUI界面
            createGUI() {
                // 创建主菜单GUI
                const advancedTexture = BABYLON.GUI.AdvancedDynamicTexture.CreateFullscreenUI("UI");
                
                // 创建信息面板
                this.infoPanel = new BABYLON.GUI.StackPanel();
                this.infoPanel.width = "250px";
                this.infoPanel.top = "10px";
                this.infoPanel.left = "10px";
                this.infoPanel.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT;
                this.infoPanel.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP;
                this.infoPanel.background = "rgba(0, 0, 0, 0.7)";
                this.infoPanel.paddingTop = "10px";
                this.infoPanel.paddingLeft = "10px";
                this.infoPanel.paddingRight = "10px";
                this.infoPanel.paddingBottom = "10px";
                advancedTexture.addControl(this.infoPanel);
                
                // 面板标题
                const header = new BABYLON.GUI.TextBlock();
                header.text = "加载的网格";
                header.color = "white";
                header.fontSize = 18;
                header.height = "30px";
                header.textHorizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT;
                this.infoPanel.addControl(header);
                
                // 分隔线
                const line = new BABYLON.GUI.Line();
                line.x1 = 0;
                line.y1 = 0;
                line.x2 = 230;
                line.y2 = 0;
                line.color = "white";
                line.thickness = 1;
                this.infoPanel.addControl(line);
                
                // 网格列表容器
                this.meshList = new BABYLON.GUI.StackPanel();
                this.meshList.isVertical = true;
                this.infoPanel.addControl(this.meshList);
            }
            
            // 注册场景
            registerScene(sceneName, config) {
                this.scenes[sceneName] = {
                    name: sceneName,
                    assetUrl: config.assetUrl,
                    assetFilename: config.assetFilename,
                    isLoaded: false,
                    setupCamera: config.setupCamera,
                    camera: null,
                    light: null
                };
            }
            
            // 加载场景资源
            async loadScene(sceneName) {
                const sceneConfig = this.scenes[sceneName];
                if (!sceneConfig) {
                    console.error(`场景 "${sceneName}" 不存在`);
                    return;
                }
                
                if (sceneConfig.isLoaded) {
                    console.log(`场景 "${sceneName}" 已加载`);
                    return;
                }
                
                // 创建场景
                const scene = new BABYLON.Scene(this.engine);
                scene.clearColor = new BABYLON.Color3(0.8, 0.8, 0.8);
                
                // 设置相机
                sceneConfig.camera = sceneConfig.setupCamera(scene);
                
                // 设置光源
                sceneConfig.light = new BABYLON.HemisphericLight(
                    `${sceneName}Light`, 
                    new BABYLON.Vector3(0, 1, 0), 
                    scene
                );
                sceneConfig.light.intensity = 0.7;
                
                // 加载资产
                return new Promise((resolve, reject) => {
                    BABYLON.SceneLoader.LoadAssetContainer(
                        sceneConfig.assetUrl,
                        sceneConfig.assetFilename,
                        scene,
                        (container) => {
                            this.assetContainers[sceneName] = container;
                            sceneConfig.isLoaded = true;
                            
                            // 如果是机器人模型，添加动画
                            if (sceneName === "scene2") {
                                this.setupRobotAnimations(scene);
                            }
                            
                            console.log(`场景 "${sceneName}" 加载完成`);
                            resolve(scene);
                        },
                        null,
                        (error) => {
                            console.error(`加载场景 "${sceneName}" 时出错:`, error);
                            reject(error);
                        }
                    );
                });
            }
            
            // 设置机器人动画
            setupRobotAnimations(scene) {
                // 查找机器人网格
                const robot = scene.getMeshByName("RobotMesh");
                if (robot) {
                    // 设置机器人动画
                    const animations = scene.animations;
                    if (animations.length > 0) {
                        scene.beginAnimation(animations[0], 0, 100, true, 1.0);
                    }
                }
            }
            
            // 切换到指定场景
            async switchToScene(sceneName) {
                // 如果当前场景已加载，先卸载
                if (this.currentScene && this.currentSceneName) {
                    this.unloadCurrentScene();
                }
                
                // 加载目标场景
                await this.loadScene(sceneName);
                
                // 显示场景
                this.currentScene = this.scenes[sceneName];
                this.currentSceneName = sceneName;
                
                // 添加资产到场景
                const container = this.assetContainers[sceneName];
                container.addAllToScene();
                
                // 更新网格信息
                this.updateMeshInfo(container.meshes);
                
                console.log(`已切换到场景: ${sceneName}`);
            }
            
            // 卸载当前场景
            unloadCurrentScene() {
                if (!this.currentScene || !this.currentSceneName) {
                    return;
                }
                
                // 移除所有实例
				for(var mesh of this.currentInstances) {
					mesh.dispose();
				}
                this.currentInstances = [];
                
                // 从场景中移除资产
                const container = this.assetContainers[this.currentSceneName];
                if (container) {
                    container.removeAllFromScene();
                }
                
                // 隐藏信息面板
                this.infoPanel.isVisible = false;
                
                console.log(`已卸载场景: ${this.currentSceneName}`);
                this.currentScene = null;
                this.currentSceneName = null;
            }
            
            // 克隆当前场景中的模型
            cloneCurrentModel() {
                if (!this.currentScene || !this.currentSceneName || !this.assetContainers[this.currentSceneName]) {
                    console.log("没有加载的场景或模型");
                    return;
                }
                
                const container = this.assetContainers[this.currentSceneName];
                const instances = container.instantiateModelsToScene(false);
                
                // 移动克隆体位置
                const positionOffset = this.currentInstances.length * 3;
				for(var mesh of instances.rootNodes) {
                    mesh.position.x += positionOffset;
				}
                
                this.currentInstances.push(...instances.rootNodes);
                
                // 更新网格信息
                this.updateMeshInfo(this.currentInstances);
                
                console.log(`克隆了 ${instances.length} 个网格`);
            }
            
            // 更新网格信息显示
            updateMeshInfo(meshes) {
                // 清空现有列表
                while (this.meshList.children.length > 0) {
                    this.meshList.removeControl(this.meshList.children[0]);
                }
                
                // 添加网格数量
                const countText = new BABYLON.GUI.TextBlock();
                countText.text = "网格数量: " + meshes.length;
                countText.color = "white";
                countText.fontSize = 14;
                countText.height = "25px";
                countText.textHorizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT;
                this.meshList.addControl(countText);
                
                // 添加所有网格名称
				for(var mesh of meshes) {
                    const meshText = new BABYLON.GUI.TextBlock();
                    meshText.text = mesh.name;
                    meshText.color = "white";
                    meshText.fontSize = 14;
                    meshText.height = "25px";
                    meshText.textHorizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT;
                    this.meshList.addControl(meshText);
				}
                
                this.infoPanel.isVisible = meshes.length > 0;
            }
            
            // 获取当前场景
            getCurrentScene() {
                return this.currentScene ? this.currentScene.camera.getScene() : this.mainScene;
            }
        }
        
        // 初始化场景管理器
        const sceneManager = new SceneManager(engine);
        
        // 设置按钮事件
        document.getElementById('loadBtn').addEventListener('click', function() {
            const sceneSelector = document.getElementById('sceneSelector');
            const selectedScene = sceneSelector.value;
            sceneManager.switchToScene(selectedScene);
        });
        
        document.getElementById('unloadBtn').addEventListener('click', function() {
            sceneManager.unloadCurrentScene();
        });
        
        document.getElementById('cloneBtn').addEventListener('click', function() {
            sceneManager.cloneCurrentModel();
        });
        
        // 初始加载主菜单
        sceneManager.switchToScene("mainMenu");
        
        // 渲染循环 - 这是必需的！
        engine.runRenderLoop(function() {
            const currentScene = sceneManager.getCurrentScene();
            if (currentScene) {
                currentScene.render();
            }
        });
        
        // 响应窗口大小变化
        window.addEventListener('resize', function() {
            engine.resize();
        });
    </script>
</body>
</html>    